﻿<!DOCTYPE html>
<html>
<head>
    <title>aes demo</title>
    <meta charset="utf-8"/>
    <style>
        *{margin:0;padding:0}
        .demo-wrap{width: 400px;height: 50px;margin: 50px auto auto auto}
    </style>
    <script src="aes.js"></script>
    <!-- <script src="./components/pad-zeropadding.js"></script> -->
</head>
<body>
<div class="demo-wrap" style="float:left; padding-top:5px;padding-left:15px;">
    <input type="text" id="data-ipt"/>
    <button onclick="getAES();">AES加密</button>
    <button onclick="getDAes();">AES解密</button>
    <br/>
    输入内容:
    <p id = "data"></p>
    <br/>
    加密后的数据:
    <p id = "encrypted"></p>
    <br/>
    解密后的数据:
    <p id="decrypted"></p>
</div>
<script>

    //var data = "5E4A8D8012C544CB9B65285FD10F04271484793021281GET/api/v1/test/mail";
    var key  = '41422321AC0A9849FDCA2904A750A45E';
    //var iv   = '0000000000000000';

    function getAesString(data){//加密
        //var key  = CryptoJS.enc.Hex.parse(key);
        //var iv = CryptoJS.enc.Latin1.parse(iv);
        var keys  = CryptoJS.enc.Utf8.parse(key);
        var iv = CryptoJS.enc.Utf8.parse(key.substring(16));
        var encrypted = CryptoJS.AES.encrypt(data,keys,
        	{
                iv:iv,
                keySize: 256,
                mode:CryptoJS.mode.CBC,
                padding:CryptoJS.pad.Pkcs7
            });
        return encrypted.toString();
        console.log(encrypted.toString());
        //return encrypted.ciphertext.toString().toUpperCase();
    }
    function getDAesString(encrypted){//解密
	//var key  = CryptoJS.enc.Hex.parse(key);
	//var iv   = CryptoJS.enc.Latin1.parse(iv);
	var keys  = CryptoJS.enc.Utf8.parse(key);
	var iv = CryptoJS.enc.Utf8.parse(key.substring(16));
	var decrypted = CryptoJS.AES.decrypt(encrypted,keys,
		{
			iv:iv,
			mode:CryptoJS.mode.CBC,
			padding:CryptoJS.pad.Pkcs7
	});
	return decrypted.toString(CryptoJS.enc.Utf8);
    }
    function getAES(){ //加密
        var data = document.getElementById("data-ipt").value;//明文
        document.getElementById("data").innerHTML = data;
        var encrypted = getAesString(data); //密文
        document.getElementById("encrypted").innerHTML = encrypted;
    }

    function getDAes(){//解密
        var encrypted = document.getElementById("encrypted").innerHTML; //密文
        var decryptedStr = getDAesString(encrypted);
        document.getElementById("decrypted").innerHTML = decryptedStr;
    }

</script>
</body>
</html>